package com.example.ecommerce.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.ecommerce.entity.Order;
import com.example.ecommerce.entity.Product;
import com.example.ecommerce.entity.User;
import com.example.ecommerce.mapper.OrderMapper;
import com.example.ecommerce.mapper.ProductMapper;
import com.example.ecommerce.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.RuntimeErrorException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    public User login(String username, String password) {
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", username).eq("password", password);
        return userMapper.selectOne(query);
    }

    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }

    @Transactional
    public boolean deleteUser(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 管理员不能删除
        if (user.getLevel() == 3) {
            throw new RuntimeException("不能删除管理员用户");
        }

        // 顾客 - 先删除订单
        if (user.getLevel() == 1) {
            QueryWrapper<Order> orderQuery = new QueryWrapper<>();
            orderQuery.eq("uid", id);
            long orderCount = orderMapper.selectCount(orderQuery);

            if (orderCount > 0) {
                int deleted = orderMapper.delete(orderQuery);
                if (deleted != orderCount) {
                    throw new RuntimeException("订单删除失败，已删除" + deleted + "/" + orderCount);
                }
            }
        }
        // 商家 - 先删除商品
        else if (user.getLevel() == 2) {
            QueryWrapper<Product> productQuery = new QueryWrapper<>();
            productQuery.eq("uid", id);
            long productCount = productMapper.selectCount(productQuery);

            if (productCount > 0) {
                int deleted = productMapper.delete(productQuery);
                if (deleted != productCount) {
                    throw new RuntimeException("商品删除失败，已删除" + deleted + "/" + productCount);
                }
            }
        }

        // 最后删除用户
        return userMapper.deleteById(id) > 0;
    }



    public boolean register(User user) {
        // 检查用户名是否已存在
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("username", user.getUsername());
        User existing = userMapper.selectOne(query);

        if (existing != null) {
            return false;
        }
        if (user.getLevel() == null) {
            user.setLevel(1);
        }

        return userMapper.insert(user) > 0;
    }

    public List<User> getAllUsersWithStats() {
        List<User> users = userMapper.selectList(null);
        return users.stream().map(user -> {
            Map<String, Object> stats = new HashMap<>();
            if (user.getLevel() == 1) {
                QueryWrapper<Order> orderQuery = new QueryWrapper<>();
                orderQuery.eq("uid", user.getId());
                long orderCount = orderMapper.selectCount(orderQuery);
                user.setOrderCount((int) orderCount);
            } else if (user.getLevel() == 2) {
                QueryWrapper<Product> productQuery = new QueryWrapper<>();
                productQuery.eq("uid", user.getId());
                long productCount = productMapper.selectCount(productQuery);
                user.setProductCount((int) productCount);
            }
            return user;
        }).collect(Collectors.toList());
    }

    public List<Order> getUserOrders(Long uid) {
        QueryWrapper<Order> query = new QueryWrapper<>();
        query.eq("uid", uid);
        return orderMapper.selectList(query);
    }

    public List<Product> getMerchantProducts(Long uid) {
        QueryWrapper<Product> query = new QueryWrapper<>();
        query.eq("uid", uid);
        return productMapper.selectList(query);
    }

    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }

    public List<User> searchUsers(String query){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("name",query).or().like("username",query);
        return userMapper.selectList(wrapper);
    }

    public boolean updateUser(User user){
        User existing = userMapper.selectById(user.getId());
        if(existing==null){
            throw new RuntimeException("用户不存在");
        }
        existing.setName(user.getName());
        existing.setLevel(user.getLevel());
        if(user.getPassword()!=null&&!user.getPassword().isEmpty()){
            existing.setPassword(user.getPassword());
        }
        return userMapper.updateById(existing)>0;
    }
}

